<?php

namespace App\Http\Controllers\Article;

use App\Events\Rank;
use App\Events\Share;
use App\Http\Controllers\BaseController;
use App\Models\Article;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class IndexController extends BaseController
{
    public function index(Request $request)
    {

        $param = $this->validate($request,[
            'type' => 'in:1,2,3,4,5',
            'keyword' => 'string|max:60',
            'category_id' => 'integer',
            'circle_id' => 'integer',
            'user_id' => 'integer',
            'firm_id' => 'integer',
            'winnow' => 'integer',
            'view' => 'integer',
            'profession_id' => 'integer',
        ]);

        $user_id = auth('api')->id();


        $str = isset($param['user_id'])  ? 'friend_id='.$param['user_id'] : 'friend_id=articles.user_id';
        $query = Article::query()
                ->select(DB::raw('*,(select sum(view_count) from article_browses where article_id=articles.id) as view_count,
                    (select count(id) from user_like_articles where article_id=articles.id and status=1) as like_count,
                    (select count(friend_id) from user_follows where '.$str.' and status=1 and user_id='.$user_id.') as is_follow,
                    (select count(id) from user_collect_articles where article_id=articles.id and status=1 and user_id='.$user_id.') as is_collect,
                    (select count(id) from user_like_articles where article_id=articles.id and status=1 and user_id='.$user_id.') as is_like,
                    (select count(id) from user_like_articles where status=1 and article_id=articles.id) as like_count,
                    (select count(id) from user_collect_articles where status=1 and article_id=articles.id) as collect_count,
                    (select count(id) from article_comments where status=2 and article_id=articles.id) as comment_count,
                    (select sum(share_count) from article_shares where article_id=articles.id) as share_count'
                ));
        if (isset($param['type']) && $param['type']!==''){
            $query->where('type',$param['type']);
        }

        if (isset($param['category_id']) && $param['category_id']!==''){

            $query->where('category_id',$param['category_id']);
        }


        if (isset($param['firm_id']) && $param['firm_id']!==''){
            $firm_id = $param['firm_id'];
            $query->whereHas('firm',function ($q) use ($firm_id){
                $q->where('id',$firm_id);
            });
        }

        if (isset($param['profession_id'])){
            $profession_id = $param['profession_id'];
            $query->whereHas('firms',function ($q) use ($profession_id){
                $q->where('profession_id',$profession_id);
            });
        }


        if (isset($param['keyword']) && $param['keyword']!==''){
            $query->where('title','like','%'.$param['keyword'].'%');
        }

        if (isset($param['circle_id']) && $param['circle_id'] !==''){
            $query->where('circle_id',$param['circle_id']);
        }

        if (isset($param['user_id']) && $param['user_id'] !==''){
            $query->where('user_id',$param['user_id']);
        }

        if (isset($param['winnow']) && $param['winnow']!==''){

            $query->orderByDesc('like_count');
        }


        if (isset($param['view']) && $param['view']!==''){

            $query->orderByDesc('view_count');
        }


        $paginate =  $query->orderBy('sort')
                            ->with(['user:id,nickname,avatar,auth' => ['title:id,title'],'identity:user_id,identity'])
                            ->where('audit_status',2)
                            ->where('status',1)
                            ->orderByDesc('id')
                            ->simplePaginate();


        return $this->success($paginate);

    }


    public function share(Request $request)
    {
        $param = $this->validate($request,[
            'article_id' => 'required|integer'
        ]);

        $user_id = auth('api')->id();
        $share_id  = DB::table('article_shares')
                    ->where('user_id',$user_id)
                    ->where('article_id',$param['article_id'])
                    ->whereDate('share_time',date('Y-m-d'))
                    ->value('id');

        if (!$share_id){
           $result = DB::table('article_shares')->insert([
                'user_id' => $user_id,
                'article_id' => $param['article_id'],
                'share_count' => 1,
                'share_time' => date('Y-m-d H:i:s')
            ]);
        }else{
            $result = DB::table('article_shares')
                        ->where('id',$share_id)
                        ->increment('share_count');
        }

        event(new Share($user_id));

        return $result ? $this->success() : $this->error();
    }


    public function show(Request $request)
    {
        $param = $this->validate($request,[
            'article_id' => 'required|integer',
        ]);


        $user_id = auth('api')->id();
        $article = Article::query()
                          ->withCount('score')
                          //->selectRaw('articles.*,')
                          ->with(['user:id,nickname,avatar,user_title_id,auth' => ['title:id,title','identity:user_id,identity','member' => function($q){
                              $q->with('member:id,name')->where('end_time','>',time());
                          }]]) ->select(DB::raw('*,(select count(id) from user_like_articles where article_id=articles.id and status=1) as like_count,
                (select count(friend_id) from user_follows where friend_id=articles.user_id and user_id='.$user_id.' and status=1) as is_follow,
                    (select count(id) from user_collect_articles where article_id=articles.id and status=1 and user_id='.$user_id.') as is_collect,
                    (select count(id) from user_like_articles where article_id=articles.id and status=1 and user_id='.$user_id.') as is_like,
                    (select count(id) from user_like_articles where status=1 and article_id=articles.id) as like_count,
                    (select count(id) from user_collect_articles where status=1 and article_id=articles.id) as collect_count,
                    (select count(id) from article_comments where audit_status=2 and article_id=articles.id) as comment_count,
                    (select sum(share_count) from article_shares where article_id=articles.id) as share_count,
                    (select sum(view_count) from article_browses where article_id=articles.id) as view_count'
            ))->where('id',$param['article_id'])->first();

        $user_id = auth('api')->id();

        $browse_id =  DB::table('course_browses')
            ->whereDate('view_time',date('Y-m-d'))
            ->where('user_id',$user_id)
            ->value('id');


        if (!$browse_id){
             DB::table('article_browses')
                ->insert([
                    'article_id' => $param['article_id'],
                    'user_id' => $user_id,
                    'view_count' => 1,
                    'view_time' => date('Y-m-d H:i:s')
                ]);
        }else{
             DB::table('article_browses')->where('id',$browse_id)->increment('view_count');
        }


        $article  = $article->toArray();

        $article['score_count'] = DB::table('article_scores')
                                    ->where('article_id',$param['article_id'])
                                    ->groupBy('user_id')
                                    ->count('user_id');

        return $this->success($article);
    }

    public function store(Request $request)
    {
        $param = $this->validate($request,[
            'type' => 'in:1,2,3,4,5',
            'category_id' => 'required_if:type,4|integer',
            'title' => 'required|max:255',
            'stats' => 'required_if:type,4|in:1,2',
            'content' => 'required_if:type,4',
            'media_type' => 'required|in:1,2',
            'media_url' => 'array',
            'cover'=> 'max:255',
            'circle_id' => 'integer'
        ]);

        $param['user_id'] = auth('api')->id();
        if (isset($param['circle_id'])){
            $param['circle_id'] = $param['circle_id'];
        }

        $article = Article::query()->create($param);

        if ($article->getKey()){
            event(new \App\Events\Article($article));
            return $this->success();
        }

        return  $this->error();

    }
}
